/**
* jQuery dotNet Plugin - http://code.google.com/p/jquerydotnetplugin/
* Copyright (c) 2008 Walter Poch (http://wpoch.com.ar || http://wpoch.wordpress.com)
* Licensed under the GPL (http://www.gnu.org/copyleft/gpl.html) license.
*
* $Date: 2008-09-05
*
* $Date: 2009-03-13 by bigsan.chen@gmail.com
*	(^) remove evalJSON helper method, because jQuery will return json object itself.
*	(+) add serialize function detection. Now we can call service like this: $.callDotNet(urlMethod, jsonData, onSuccess);
*
*/
// Plugin definition
(function($) {
	// Plugin implementation
	$.callDotNet = function(url, data, callback) {
		// Helper method
		var serialize = function(object) {
			if (typeof (object) == "string") {
				return object;
			}

			var f = (window["Sys"] && Sys.Serialization && Sys.Serialization.JavaScriptSerializer.serialize) || (window["JSON"] && JSON.stringify);
			if ($.isFunction(f)) {
				return f(object);
			}
			else {
				var msg = "Cannot find serializer function, try the following solution:\n\n";
				msg += " 1. Make sure there is a ScriptManger server control on your page, or\n";
				msg += " 2. get JSON javascript from http://www.json.org/js.html, or\n";
				msg += " 3. pass in manually serialized string type data parameter.\n";
				throw new Error(-1, msg);
			}
		}


		// shift arguments if data argument was ommited
		if ($.isFunction(data)) {
			callback = data;
			data = "{}";
		}

		data = serialize(data);

		return $.ajax({
			type: "POST",
			url: url,
			data: data,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
				return callback(msg.d);
			},
			error: $.callDotNet.onError
		});
	}

	// Default implementation of the error function
	$.callDotNet.onError = function(error) {
		alert("There was an error processing your request.\n"
                    + "[" + error.status + "]"
                    + " [" + error.statusText + "]");
	}
})(jQuery);